package com.example.teaching_server.service;

import com.example.teaching_server.dto.TeacherDashboardDTO;
import com.example.teaching_server.entity.ActivityEntity;
import com.example.teaching_server.entity.TeachingResource;
import com.example.teaching_server.entity.TeacherTool;
import com.example.teaching_server.repository.ActivityRepository;
import com.example.teaching_server.repository.TeachingResourceRepository;
import com.example.teaching_server.repository.TeacherToolRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 教师仪表板服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class TeacherDashboardService {

    private final ActivityRepository activityRepository;
    private final TeachingResourceRepository teachingResourceRepository;
    private final TeacherToolRepository teacherToolRepository;

    /**
     * 获取教师仪表板数据
     */
    public TeacherDashboardDTO getDashboardData(Long userId) {
        log.debug("获取教师仪表板数据: userId={}", userId);

        TeacherDashboardDTO dto = new TeacherDashboardDTO();
        dto.setTools(getTools());
        dto.setResources(getResourceData(userId));
        dto.setClassActivities(getClassActivityData(userId));
        dto.setCertificates(getCertificates());
        return dto;
    }

    /**
     * 获取工具数据
     */
    private List<TeacherDashboardDTO.ToolDTO> getTools() {
        log.debug("获取教师工具数据");

        List<TeacherTool> tools = teacherToolRepository.findByIsActiveTrueOrderBySortOrderAsc();
        return tools.stream()
                .map(this::convertToToolDTO)
                .collect(Collectors.toList());
    }

    /**
     * 获取资源数据
     */
    private List<TeacherDashboardDTO.ResourceDTO> getResourceData(Long userId) {
        log.debug("获取教师资源数据: userId={}", userId);

        List<TeacherDashboardDTO.ResourceDTO> result = new ArrayList<>();
        List<TeachingResource> teachingResources = teachingResourceRepository.findTop4ByOrderByCreatedAtDesc();

        for (int i = 0; i < teachingResources.size(); i++) {
            TeachingResource resource = teachingResources.get(i);
            String resourceType = i < 2 ? "class" : "subscription";
            result.add(convertTeachingResourceToResourceDTO(resource, resourceType));
        }

        return result;
    }

    /**
     * 获取班级活动数据
     */
    private List<TeacherDashboardDTO.ClassActivityDTO> getClassActivityData(Long userId) {
        log.debug("获取班级活动数据: userId={}", userId);

        List<TeacherDashboardDTO.ClassActivityDTO> result = new ArrayList<>();

        // 我的活动
        List<ActivityEntity> myActivities = activityRepository.findMyActivities(userId, 4)
                .stream()
                .limit(2)
                .toList();
        myActivities.forEach(a -> result.add(convertActivity(a, "mine")));

        // 所有活动（排除我的活动）
        List<Long> myActivityIds = myActivities.stream()
                .map(ActivityEntity::getId)
                .toList();

        List<ActivityEntity> allActivities = activityRepository.findAllActivitiesLimit(4)
                .stream()
                .filter(a -> !myActivityIds.contains(a.getId()))
                .limit(2)
                .toList();
        allActivities.forEach(a -> result.add(convertActivity(a, "all")));

        return result;
    }

    /**
     * 获取证书数据
     */
    private List<TeacherDashboardDTO.CertificateDTO> getCertificates() {
        log.debug("获取证书数据");

        return Arrays.asList(
                createCertificate(1L, "教学质量满意度调查", "published", "2023-11-01",
                        "2023-2024学年第一学期教学质量评估", 42, null),
                createCertificate(4L, "学生心理健康调查", "answered", "2023-10-15",
                        "学生心理健康状况匿名调查", null, "2023-10-16")
        );
    }

    /**
     * 转换工具实体为DTO
     */
    private TeacherDashboardDTO.ToolDTO convertToToolDTO(TeacherTool tool) {
        TeacherDashboardDTO.ToolDTO dto = new TeacherDashboardDTO.ToolDTO();
        dto.setName(tool.getName());
        dto.setIcon(tool.getIcon());
        return dto;
    }

    /**
     * 转换教学资源为资源DTO
     */
    private TeacherDashboardDTO.ResourceDTO convertTeachingResourceToResourceDTO(TeachingResource resource, String resourceType) {
        TeacherDashboardDTO.ResourceDTO dto = new TeacherDashboardDTO.ResourceDTO();
        dto.setId(resource.getId());
        dto.setTitle(resource.getTitle());
        dto.setType("教学资源");
        dto.setUpdatedAt(getFormattedDate(resource));
        dto.setCategory(resourceType);
        dto.setUrl(resource.getFileUrl());
        dto.setFileType(getFileTypeFromUrl(resource.getFileUrl()));
        return dto;
    }

    /**
     * 转换活动实体为活动DTO
     */
    private TeacherDashboardDTO.ClassActivityDTO convertActivity(ActivityEntity activity, String type) {
        TeacherDashboardDTO.ClassActivityDTO dto = new TeacherDashboardDTO.ClassActivityDTO();
        dto.setId(activity.getId());
        dto.setTitle(activity.getTitle());
        dto.setType(type);
        dto.setDate(getActivityDate(activity));
        dto.setStatus(getActivityStatus(activity));
        dto.setImage(null);
        dto.setDescription(activity.getDescription());
        return dto;
    }

    /**
     * 创建证书DTO
     */
    private TeacherDashboardDTO.CertificateDTO createCertificate(Long id, String title, String type, String date,
                                                                 String description, Integer responses, String submitted) {
        TeacherDashboardDTO.CertificateDTO cert = new TeacherDashboardDTO.CertificateDTO();
        cert.setId(id);
        cert.setTitle(title);
        cert.setType(type);
        cert.setDate(date);
        cert.setDescription(description);
        cert.setResponses(responses);
        cert.setSubmitted(submitted);
        return cert;
    }

    /**
     * 获取格式化日期
     */
    private String getFormattedDate(TeachingResource resource) {
        if (resource.getUpdatedAt() != null) {
            return resource.getUpdatedAt().toLocalDate().toString();
        } else if (resource.getCreatedAt() != null) {
            return resource.getCreatedAt().toLocalDate().toString();
        }
        return "";
    }

    /**
     * 获取活动日期
     */
    private String getActivityDate(ActivityEntity activity) {
        return activity.getStartDate() != null ? activity.getStartDate().toString() : "";
    }

    /**
     * 获取活动状态
     */
    private String getActivityStatus(ActivityEntity activity) {
        LocalDate now = LocalDate.now();
        if (activity.getStartDate() != null && now.isBefore(activity.getStartDate())) {
            return "upcoming";
        }
        if (activity.getEndDate() != null && now.isAfter(activity.getEndDate())) {
            return "finished";
        }
        return "ongoing";
    }

    /**
     * 从文件URL获取文件类型
     */
    private String getFileTypeFromUrl(String fileUrl) {
        if (fileUrl == null) return "unknown";

        String lowerUrl = fileUrl.toLowerCase();
        if (lowerUrl.contains(".pdf")) return "pdf";
        if (lowerUrl.contains(".doc") || lowerUrl.contains(".docx")) return "word";
        if (lowerUrl.contains(".ppt") || lowerUrl.contains(".pptx")) return "ppt";
        if (lowerUrl.contains(".xls") || lowerUrl.contains(".xlsx")) return "excel";
        if (lowerUrl.contains(".mp4") || lowerUrl.contains(".avi")) return "video";
        if (lowerUrl.contains(".jpg") || lowerUrl.contains(".png")) return "image";

        return "document";
    }
}
